package LeetCode.exercise;

import java.util.HashMap;

public class LC904 {
    public static int totalFruit(int[] fruits) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        int res = 0;
        for (int left = 0, right = 0; right < fruits.length; right++) {
            hashMap.put(fruits[right],
                    hashMap.get(fruits[right]) == null ? 1 : hashMap.get(fruits[right]) + 1);
            while (hashMap.size() > 2) {
                hashMap.put(fruits[left], hashMap.get(fruits[left]) - 1);
                if (hashMap.get(fruits[left]) == 0) {
                    hashMap.remove(fruits[left]);
                }
                left++;
            }
            res = Math.max(res, right - left + 1);
        }
        return res;
    }

    public static void main(String[] args) {
        totalFruit(new int[]{0,1,2,2});
        totalFruit(new int[]{1,2,3,2,2});
    }
}

